import axios from 'axios'
import { tansParams } from '@/until/paramRou'
import { Notification, Message, Loading } from 'element-ui'
import router from '@/router/index';
import storages from './localStorage';

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
let loading
function startLoding () {
  loading = Loading.service({
    lock: true,
    spinner: 'el-icon-loading',
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
}
function endLoading () {
  loading.close()
}

const service = axios.create({
  baseURL: '',
  // 超时
  timeout: 30000
})
// request拦截器
service.interceptors.request.use(config => {
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  // 是否需要防止数据重复提交
  const isRepeatSubmit = (config.headers || {}).repeatSubmit === false
  if (storages.getItem('Admin-Token') && !isToken) {
    config.headers.Authorization = 'Bearer ' + storages.getItem('Admin-Token') // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  // get请求映射params参数
  if (config.method === 'get' && config.param) {
    let url = config.url + '?' + tansParams(config.param)
    url = url.slice(0, -1)
    config.param = {}
    config.url = url
  }
  if (!isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
    const requestObj = {
      url: config.url,
      data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data
    }
    const requestSize = Object.keys(JSON.stringify(requestObj)).length // 请求数据大小
    const limitSize = 5 * 1024 * 1024 // 限制存放数据5M
    if (requestSize >= limitSize) {
      console.warn(`[${config.url}]: ` + '请求数据大小超出允许的5M限制，无法进行防重复提交验证。')
      return config
    }
  }
  startLoding()
  return config
}, error => {
  Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
  endLoading()
  // 未设置状态码则默认成功状态
  
  const code = res.data.code || '200'
  // 二进制数据则直接返回
  if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
    return res.data
  }
  const msg = res.data.message
  if (code === '-4003') {
    router.push('/login')
    return res.data
    // return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
  } else if (code === '5000') {
    Message({ message: msg, type: 'error' })
    return res.data
  } else if (code === '601') {
    Message({ message: msg, type: 'warning' })
    return res.data
  } else if (code === '200') {
    return res.data
    // return Promise.reject('error')
  } else {
    return res.data
  }
},
error => {
  let { message } = error
  // console.log(error,message);
  
  if (message === 'Network Error') {
    message = '连接异常'
  } else if (message.includes('timeout')) {
    // console.log(1231231321);
    
    message = '服务器忙~'
  } else if (message.includes('Request failed with status code')) {
    message = '系统接口' + message.substr(message.length - 3) + '异常'
  } else if(message === 'timeout of 10000ms exceeded') {
    message = '服务升级中...'
    router.push('/login')
  }
  Message({ message: message, type: 'error', duration: 5 * 1000 })
  // return Promise.reject(error)
}
)

export default service
